# -*- utf:8 -*-
import os
import os, django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "api_automation_test.settings")
django.setup()

import xlsxwriter
from django.http import JsonResponse
from rest_framework.authentication import TokenAuthentication
from rest_framework.views import APIView

from backend.models import Lyzd_Interface, Lyzd_Interface_Header, Sys_Project, Lyzd_Interface_Param
from backend.serializers import Sys_InterfaceSerializer, AutomationGroupLevelFirstSerializer, SysEnvironmentSerializer


def interface_template_download():
    randomName = '接口模板下载'
    # data = AutomationCaseDownSerializer(obi, many=True).data
    path = "./backend/interface/temp/"
    fileName = '%s.xlsx' % (randomName)
    filePath = path + '%s.xlsx' % (randomName)
    workbook = xlsxwriter.Workbook(filePath)
    # 新建一个worksheet
    worksheet = workbook.add_worksheet()
    title = ['*所属项目', '*项目模块', '*接口名称', '*方法名称', '请求方式（为空时默认为POST请求）', '是否加密（1是0否）', '加密URL', '解密URL', 'Headerkey',
             '参数类型','HeaderkeyValue',
             '是否依赖', '依赖名称', '依赖key', 'paramkey', '参数类型', '是否依赖', '依赖名称', '依赖key', '入参', '出参']

    # 向'A1'单元格写入title列表，列表中每一个字段对应一列内容
    worksheet.write_row("A1", title)
    # 给excel单元格除了第一行以外的前100行设置有效性数据
    # for i in range(2,100):
    #     list=[i]
    #     worksheet.data_validation("A"+str(list[0]), {'validate': 'list', 'source': model_name})
    #     worksheet.data_validation("B"+str(list[0]), {'validate': 'list', 'source': project_name})
    workbook.close()
    return filePath

# interface_name = Lyzd_Interface.objects.values('interface_name_zh').get(id__exact=2)
# print(interface_name)

def case_template_download(project_id, interface_id):
    # 新建一个Excel文件
    randomName = '用例模板下载'
    # data = AutomationCaseDownSerializer(obi, many=True).data
    path = "./backend/interface/temp/"
    # path = "./"
    fileName = '%s.xlsx' % (randomName)
    filePath = path + '%s.xlsx' % (randomName)
    workbook = xlsxwriter.Workbook(filePath)
    # 新建一个worksheet
    worksheet = workbook.add_worksheet()
    interface_name = Lyzd_Interface.objects.values('interface_name_zh').get(id__exact=interface_id)
    print(interface_name)
    interface_name = interface_name['interface_name_zh']
    project_name = Sys_Project.objects.values('project_name').get(id__exact=project_id)
    project_name = project_name['project_name']
    title = ['*所属项目：', project_name, '*接口名称：', interface_name]
    title1 = ['*用例分类', '*用例名称', '*校验分类', '执行条件', '校验key', '校验条件', '执行sql', '预期值']
    # 根据接口id将相关联的headerkey查询出来并添加到数组中
    # header_key = Lyzd_Interface_Header.objects.values('header_key').filter(interface_id__exact=interface_id)
    # for a in range(0, len(header_key)):
    #     # 添加元素到list列表的指定位置
    #     title1.insert(a + 2, header_key[a]['header_key'])
    # # 根据接口id将相关联的paramkey查询出来并添加到数组中
    # param_key = Lyzd_Interface_Param.objects.values('param_key').filter(interface_id__exact=interface_id)
    # for a in range(0, len(param_key)):
    #     # 添加元素到list列表的指定位置
    #     title1.insert(a + 2 + len(header_key), param_key[a]['param_key'])
    # 根据接口id将相关联的paramkey查询出来并添加到数组中
    param_key = Lyzd_Interface_Param.objects.values('param_key').filter(interface_id__exact=interface_id)
    for a in range(0, len(param_key)):
        # 添加元素到list列表的指定位置
        title1.insert(a + 2, param_key[a]['param_key'])

    # 向'A1'单元格写入title列表，列表中每一个字段对应一列内容
    worksheet.write_row("A1", title)
    worksheet.write_row("A2", title1)
    workbook.close()
    return filePath


class InterfaceTemplateDownload(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()
    def get(self, request):
        """
        获取用例分组
        :return:
        """
        """无条件查询查询接口"""
        path = interface_template_download()
        if path:
            return JsonResponse(data={'path': path, 'code': '999999', 'msg': '成功'})
        else:
            return JsonResponse(data={'path': path, 'code': '999998', 'msg': '失败'})


# 用例模板下载
class CaseTemplateDownload(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        interface_id = request.GET.get('interface_id')
        project_id = request.GET.get('project_id')
        print(interface_id,project_id)
        """
        获取Api下载文档路径
        :param request:
        :return:
        """
        try:

            # 判断所选项目下是否存在所选接口名称
            interface = Lyzd_Interface.objects.filter(project_id__exact=project_id, id__exact=interface_id)
            if interface.count() == 0:
                return JsonResponse(data={'code': '999997', 'msg': '所选项目下不存在该接口名称，请重新选择'})
            else:
                # 调用模板下载方法，成功返回模板路径，失败返回模板下载失败
                template = case_template_download(project_id, interface_id)
                return JsonResponse(data={'code': '999999', 'msg': '下载成功', 'data': template})
        except:
            return JsonResponse(data={'code': '999998', 'msg': '下载失败'})

if __name__ == '__main__':
    case_template_download('1', '1')
